/*---------------------------------------------------------------------------
 * 
 * CHANGE RUNTIME CONSTANTS WHEN DELPOYING TO OTHER SERVER.
 * 
 ----------------------------------------------------------------------------*/
//CSV_LOGO = 'image://http://localhost:8000/templates/ppspconsole/images/csv.png';
CSV_LOGO = 'image://http://www.adgyde.com/templates/ppspconsole/images/csv.png';

function getMaxValue(values) {
	if (values.length == 0)
		return 0;

	var i, v = 0;
	for (i = 0; i < values.length; i++) {
		if (values[i] > v)
			v = values[i];
	}
	
	return v;
}

function exportAsCSV(labels, values, title) {
	if (labels.length == 0)
		return ;
	
	var i;
	var csv = '';
	for (i = 0; i < labels.length; i++) {
		csv += '"' + labels[i] + '",' + values[i] + '\r\n';
	}
	
    var a = document.createElement("a");
    a.href = 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(csv);
    a.download = 'export.csv';
    a.target = '_blank';
    document.body.appendChild(a); 
    a.click();
}

function exportPieAsCSV(values, title) {
	if (values.length == 0)
		return ;
	
	var i;
	var csv = '';
	for (i = 0; i < values.length; i++) {
		csv += '"' + values[i].name + '",' + values[i].value + '\n';
	}
	
	var a = document.createElement("a");
    a.href = 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(csv);
    a.download = 'export.csv';
    a.target = '_blank';
    document.body.appendChild(a); 
    a.click();	
}

function exportDoublePiesAsCSV(name1, name2, values1, values2, title) {
	if (values1.length == 0)
		return ;
	
	var i;
	var csv = '';
	
	if (values1.length > 0) {
		csv += name1 + '\n';
		for (i = 0; i < values1.length; i++) {
			csv += '"' + values1[i].name + '",' + values1[i].value + '\n';
		}
	}
	
	if (values2.length > 0) {
		csv += name2 + '\n';
		for (i = 0; i < values2.length; i++) {
			csv += '"' + values2[i].name + '",' + values2[i].value + '\n';
		}
	}

	var a = document.createElement("a");
    a.href = 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(csv);
    a.download = 'export.csv';
    a.target = '_blank';
    document.body.appendChild(a); 
    a.click();
}

function padZero(v) {
    v = Math.round(v);
    if (v < 10)
        return '0' + v;
    return v;
}

function formatAsTime(seconds) {
	var days = Math.trunc(seconds / (24 * 60 * 60));
	seconds = seconds % (24 * 60 * 60);
	var hours = Math.trunc(seconds / (60 * 60));
	seconds = seconds % (60 * 60);
	var minutes = Math.trunc(seconds / 60);
	seconds = seconds % 60;
	
	return days + ' day(s) ' + padZero(hours) + ':' + padZero(minutes)
		+ ':' + padZero(seconds);
}

function createLineChartFromIE(divId, title, xTitle, yTitle, data) {
    xdata = [];
    ydata = [];
    if (data.data.length > 0) {
        for (var i = 0; i < data.data.length; i++) {
            xdata.push(data.data[i].time);
            ydata.push(data.data[i].value);
        }
    }
    
    return createLineChart({
        divId: divId,
        title: title,
        isHourView: false,
        xTitle: xTitle,
        yTitle: yTitle,
        xitems: xdata,
        yitems: ydata
    });
}

/*
 * @param opt	Chart parameters object.
 * 				divId - div id of chart
 * 				title - title of chart
 * 				isHourView - true if it is hourly view
 * 				xitems - data of X axis
 * 				yitems - data of Y axis
 * 				xTitle - title of x axis
 * 				yTitle - title of y axis
 */
function createLineChart(opt) {
	var chart = echarts.init(document.getElementById(opt.divId));
	
	var maxValue = getMaxValue(opt.yitems);
	if (maxValue % 4 != 0)
    	maxValue += (4 - maxValue % 4);
	var interval = maxValue / 4;
	var downTitle=opt.yTitle +"-" + opt.title;
	option = {
        title: {
            text: opt.title,
            left: 'center',
            show: true
        },
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            containLabel: true
        },
        toolbox: {
	        right: "10%",
            feature: {
                saveAsImage: {},
                myCsvExport: {
                    show: true,
                    title: 'Save as csv',
                    icon: CSV_LOGO,
                    onclick: function() {
                    	exportAsCSV(opt.xitems, opt.yitems, downTitle);
                    }
                }
            }
        },
        xAxis: {
            type: 'category',
            name: opt.xTitle,
            boundaryGap: false,
            data: opt.xitems
        },
        yAxis: {
            name: opt.yTitle,
            //max: maxValue,
            type: 'value',
            interval: interval
        },
        series: [
            {
                type:'line',
                data: opt.yitems
            }
        ]
	};
	
	chart.setOption(option);
	if (opt.isHourView) {
		chart.setOption({
			xAxis: {
				axisLabel: {
					formatter: function (value) {
			            var date = new Date(value);
			            return date.Format("hh:mm");
			        }
				}
			}
		});
	}

	
	return chart;
}

function createDoubleLineChart(opt) {
	var chart = echarts.init(document.getElementById(opt.divId));
/*	var maxValue = getMaxValue(opt.yitems);
	if (maxValue % 4 != 0)
		maxValue += (4 - maxValue % 4);
	var interval = maxValue / 4;
	var downTitle=opt.yTitle +"-" + opt.title;*/
	option = {
		title: {
			text: opt.title,
		},
		tooltip: {
			trigger: 'axis'
		},
	    grid: {
			left: '2%',
			right: '5%',
			bottom: '3%',
			containLabel: true
		},
		toolbox: {
	        feature: {
	            saveAsImage: {}
	        }
	    },
		xAxis: {
			type: 'category',
			name: opt.xTitle,
			boundaryGap: false,
			data: opt.xitems
		},
		yAxis: [
	        {
	            name: 'DAU',
	            type: 'value',
	            //max: 500
	        },
	        {
	            name: 'Avg. Session Duration',
	            nameLocation: 'start',
	            //max: 5,
	            type: 'value',
	            inverse: true
	        }
	    ],
		series: [
			{
				type:'line',
				data: opt.yitems1,
				itemStyle: {
		            normal: {
		                color: 'rgba(67, 185, 104, 1)',
		            }
		        }
			},
			{
				type:'line',
				data: opt.yitems2,
				itemStyle: {
		            normal: {
		                color: 'rgba(244, 66, 54, 1)',
		            }
		        }
			}
		]
	};

	chart.setOption(option);
	if (opt.isHourView) {
		chart.setOption({
			xAxis: {
				axisLabel: {
					formatter: function (value) {
						var date = new Date(value);
						return date.Format("hh:mm");
					}
				}
			}
		});
	}


	return chart;
}

function createRevenueLineChart(opt) {
	var chart = echarts.init(document.getElementById(opt.divId));
/*	var maxValue = getMaxValue(opt.yitems);
	if (maxValue % 4 != 0)
		maxValue += (4 - maxValue % 4);
	var interval = maxValue / 4;
	var downTitle=opt.yTitle +"-" + opt.title;*/
	option = {
		title: {
			text: opt.title,
		},
		tooltip: {
			trigger: 'axis'
		},
	    grid: {
			left: '2%',
			right: '5%',
			bottom: '3%',
			containLabel: true
		},
		toolbox: {
	        feature: {
	            saveAsImage: {}
	        }
	    },
		xAxis: {
			type: 'category',
			name: opt.xTitle,
			boundaryGap: false,
			data: opt.xitems
		},
		yAxis: [
	        {
	            name: 'Revenue',
	            type: 'value',
	            //max: 500
	        },
	        {
	            name: 'Cost',
	            nameLocation: 'start',
	            //max: 5,
	            type: 'value',
	            inverse: true
	        }
	    ],
		series: [
			{
				type:'line',
				data: opt.yitems1,
				itemStyle: {
		            normal: {
		                color: 'rgba(67, 185, 104, 1)',
		            }
		        }
			},
			{
				type:'line',
				data: opt.yitems2,
				itemStyle: {
		            normal: {
		                color: 'rgba(244, 66, 54, 1)',
		            }
		        }
			}
		]
	};

	chart.setOption(option);
	if (opt.isHourView) {
		chart.setOption({
			xAxis: {
				axisLabel: {
					formatter: function (value) {
						var date = new Date(value);
						return date.Format("hh:mm");
					}
				}
			}
		});
	}


	return chart;
}

/*
 * Create Histogram.
 * 
 * @param opt	Chart parameters object.
 * 				divId  - div id of chart
 * 				title  - title of chart
 * 				names  - name of categories
 * 				values - data of categories
 */
function createHistogram(opt) {
	var chart = echarts.init(document.getElementById(opt.divId));
    var downTitle=opt.title;
    option = {
	    title: {
	        text: opt.title,
	        left: 'center',
	    },
	    tooltip: {
	        trigger: 'axis',
	        axisPointer: {
	            type: 'shadow'
	        }
	    },
        toolbox: {
	        right: "10%",
            feature: {
                saveAsImage: {},
                myCsvExport: {
                    show: true,
                    title: 'Save as csv',
                    icon: CSV_LOGO,
                    onclick: function() {
                    	exportAsCSV(opt.names, opt.values, downTitle );
                    }
                }
            }
        },
	    grid: {
	        left: '0',
	        right: '4%',
	        bottom: '3%',
	        containLabel: true
	    },
	    xAxis: {
	        type: 'value',
	        boundaryGap: [0, 0.01]
	    },
	    yAxis: {
	        title:'event',
	        type: 'category',
	        data: opt.names
	    },
	    series: [
	        {
	            name:'value',
	            type: 'bar',
	            data: opt.values
	        }
	    ]
	};

    chart.setOption(option);
    
    return chart;
}

/*
 * Create pie chart from Interface E
 */
function createPieChartFromIE(divId, title, data) {
    names = [];
    values = [];
    
    if (data.data.length > 0) {
        for (var i = 0; i < data.data.length; i++) {
            names.push(data.data[i].key);
            values.push({
                name: data.data[i].key,
                value: data.data[i].value
            });
        }
    }
    
    return createPieChart({
        divId: divId,
        title: title,
        names: names,
        values: values
    });
}

/*
 * Create pie chart.
 * 
 * @param opt	Chart parameters object.
 * 				divId - div id of chart
 * 				title  - title of chart
 * 				names  - name of categories
 * 				values - data of categories
 */
function createPieChart(opt) {
	var chart = echarts.init(document.getElementById(opt.divId));
    var downTitle=opt.divId+"-"+opt.title;
    option = {
	    title : {
	        text: opt.title,
	        left: 'center',
	        x:'center'
	    },
	    tooltip : {
	        trigger: 'item',
	        formatter: "{a} <br/>{b} : {c} ({d}%)"
	    },
        toolbox: {
	        right: "10%",
            feature: {
                saveAsImage: {},
                myCsvExport: {
                    show: true,
                    title: 'Save as csv',
                    icon: CSV_LOGO,
                    onclick: function() {
                    	exportPieAsCSV(opt.values, downTitle);
                    }
                }
            }
        },
	    legend: {
	        orient: 'vertical',
	        left: 'left',
	        data: opt.names
	    },
	    series : [
	        {
	            name: 'value',
	            type: 'pie',
	            radius : '55%',
	            center: ['50%', '60%'],
	            data: opt.values,
	            itemStyle: {
	                emphasis: {
	                    shadowBlur: 10,
	                    shadowOffsetX: 0,
	                    shadowColor: 'rgba(0, 0, 0, 0.5)'
	                }
	            }
	        }
	    ]
	};

    chart.setOption(option);
    
    return chart;
}

/*
 * Create double pie charts on the same div.
 * 
 * @param opt	Chart parameters object.
 * 				divId 		- id of chart div
 * 				title 		- title of chart
 * 				pie1Name 	- name of pie chart 1
 * 				pie2Name 	- name of pie chart 2
 * 				pie1Values	- values of pie chart 1
 * 				pie2Values 	- values of pie chart 2 
 */
function createDoublePieChart(opt) {
    var chart = echarts.init(document.getElementById(opt.divId));

    var names = [];
    var i;
    var downTitle=opt.divId+"-"+opt.title;
    if (opt.pie1Values.length > 0) {
    	for (i = 0; i < opt.pie1Values.length; i++) {
    		if (!(opt.pie1Values[i].name in names)) {
    			names.push(opt.pie1Values[i].name);
    		}
    	}
    }
    if (opt.pie2Values.length > 0) {
    	for (i = 0; i < opt.pie2Values.length; i++) {
			if (!(opt.pie2Values[i].name in names)) {
				names.push(opt.pie2Values[i].name);
			}
    	}
    }
    
    option = {
        title: {
            text: opt.title,
            left: 'center'
        },        
        toolbox: {
            right: "10%",
            feature: {
                saveAsImage: {},
                myCsvExport: {
                    show: true,
                    title: 'Save as csv',
                    icon: CSV_LOGO,
                    onclick: function() {
                    	exportDoublePiesAsCSV(
                    		opt.pie1Name, 
                    		opt.pie2Name, 
                    		opt.pie1Values,
                    		opt.pie2Values,
                            downTitle
                    	);
                    }
                }
            }
        },
        legend: {
            orient: 'vertical',
            x: 'left',
            top: 40,
            data: names
        },
        series: [
            {
                name: opt.pie1Name,
                type:'pie',
                selectedMode: 'single',
                radius: [0, '30%'],

                label: {
                    normal: {
                        show: false
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data: opt.pie1Values
            },
            {
                name: opt.pie2Name,
                type:'pie',
                radius: ['40%', '55%'],
                data: opt.pie2Values
            }
        ]
    };

    chart.setOption(option);
    
    return chart;
}

/*
 * Create funnel chart.
 * 
 * @param opt	Chart parameters object.
 * 				divId - chart div id
 * 				title - chart title
 * 				names - name of nodes
 * 				nodes - funnel nodes
 */
function createFunnelChart(opt) {
    var chart = echarts.init(document.getElementById(opt.divId));
    var downTitle=opt.divId+"-"+opt.title;
    option = {
	    title: {
	        text: opt.title,
	        left: 'center'
	    },
	    tooltip: {
	        trigger: 'item',
	        formatter: "{a} <br/>{b} : {c}%"
	    },
        toolbox: {
	        right: "10%",
            feature: {
                saveAsImage: {},
                myCsvExport: {
                    show: true,
                    title: 'Save as csv',
                    icon: CSV_LOGO,
                    onclick: function() {
                    	exportPieAsCSV(opt.nodes, downTitle);
                    }
                }
            }
        },
	    legend: {
		    orient: 'vertical',
		    left: '1%',
		    top: '10%',
	        data: opt.names
	    },
	    calculable: true,
	    series: [
	        {
	            //name: '<?php echo $item['title'] ?>',
	            type:'funnel',
	            left: '20%',
	            top: 60,
	            bottom: 60,
	            width: '60%',
	            minSize: '0%',
	            maxSize: '100%',
	            sort: 'none',
	            gap: 2,
	            label: {
	                normal: {
	                    show: true,
	                    position: 'inside'
	                },
	                emphasis: {
	                    textStyle: {
	                        fontSize: 20
	                    }
	                }
	            },
	            labelLine: {
	                normal: {
	                    length: 10,
	                    lineStyle: {
	                        width: 1,
	                        type: 'solid'
	                    }
	                }
	            },
	            itemStyle: {
	                normal: {
	                    borderColor: '#fff',
	                    borderWidth: 1
	                }
	            },
	            data: opt.nodes
	        }
	    ]
	};

    chart.setOption(option);
    
    return chart;
}

function createSetFrom(names) {
    var r = [];
    for (var name in names) {
        if (r.indexOf(name) == -1) {
            r.push(name);
        }
    }
    return r;
}

function getLegendsFromStackedBarChart(data) {
    var names = [];
    for (var i = 0; i < data.data.length; i++) {
        var d = data.data[i];
        for (var j = 0; j < d.series.length; j++) {
            var item = d.series[j];
            if (names.indexOf(item.item) == -1)
                names.push(item.item);
        }
    }
    
    return names;
}

function getDateFromStackedBarChart(data) {
    var names = [];
    for (var i = 0; i < data.data.length; i++) {
        names.push(data.data[i].time);
    }
    
    return names;
}

function getStackedBarChartDataSeries(name, data) {
    var result = [];
    for (var i = 0; i < data.data.length; i++) {
        var d = data.data[i];
        var v = 0;
        for (var j = 0; j < d.series.length; j++) {
            var item = d.series[j];
            if (name == item.item) {
                v = item.value;
                break;
            }
        }
        result.push(v);
    }
    
    return result;
}

/*
 * Create daily stacked bar chart.
 *
 * opt.divId - div id of chart
 * opt.data  - StackedBarChart object
 * opt.title - report title
 */
function createStackedBarChart(opt) {
	var chart = echarts.init(document.getElementById(opt.divId));
	
	var names = getLegendsFromStackedBarChart(opt.data);
	var series = [];
	for (var i = 0; i < names.length; i++) {
	    var data = getStackedBarChartDataSeries(names[i], opt.data);
	    series.push({
	        name: names[i],
	        type: 'bar',
	        stack: '总量',
	        label: {
	            normal: {
	                show: false,
	                position: 'insideRight'
	            }
	        },
	        data: data
	    });
	}
	var dates = getDateFromStackedBarChart(opt.data);
	
	option = {
		title: {
			text: opt.title,
			left: 'center',
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			}
		},
		toolbox: {
			right: "10%",
			feature: {
				saveAsImage: {},
				myCsvExport: {
					show: true,
					title: 'Save as csv',
					icon: CSV_LOGO,
					onclick: function() {
						exportAsCSV(opt.names, opt.values, downTitle );
					}
				}
			}
		},
		legend: {
		    top: 30,
		    data: names
		},
		grid: {
		    top: 80,
			left: '3%',
			right: '4%',
			bottom: '3%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			data: dates
		},
		yAxis: {
			type: 'value'
		},
		series: series
	};

	chart.setOption(option);

	return chart;
}

function createDoHistogram(opt) {
	
	var chart = echarts.init(document.getElementById(opt.divId));
	var downTitle=opt.title;
	option = {
		title: {
			text: opt.title,
			left: 'center',
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			}
		},
		toolbox: {
			right: "10%",
			feature: {
				saveAsImage: {},
				myCsvExport: {
					show: true,
					title: 'Save as csv',
					icon: CSV_LOGO,
					onclick: function() {
						exportAsCSV(opt.names, opt.values, downTitle );
					}
				}
			}
		},
		grid: {
			left: '0',
			right: '4%',
			bottom: '3%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			data: opt.times
			/*type: 'value',
			boundaryGap: [0, 0.01]*/
		},
		yAxis: {
			type: 'value',
			boundaryGap: [0, 0.01]
		},
		series:function(){
			var serie=[];
			var colorList = ['rgba(45,255,115,0.4)','rgba(62,112,201,0.4)'];
			var i=0
			for(var key in opt.series) {
			var item={
				name: key,
	            type: 'bar',
	            stack: '总量',
                itemStyle: {
	            	normal: {
	            		color: colorList[i]
	            	}
	            },
	            label: {
	                normal: {
	                    show: true,
	                    position: 'inside'
	                }
	            },

	            data: opt.series[key]
			};
				i++;
				serie.push(item);
			}
			var item2 = {
					name: 'count',
					type: 'line',
					data: opt.lines
			};

			serie.push(item2);
			return serie;
		}()

		/*[
			{
				name:'value',
				type: 'bar',
				data: opt.values
			}
		]*/
	};

	chart.setOption(option);

	return chart;
}

function createLines(opt) {

	var chart = echarts.init(document.getElementById(opt.divId));
	var downTitle=opt.title;
	option = {
		title: {
			text: opt.title,
			left: 'center',
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			}
		},
		toolbox: {
			right: "10%",
			feature: {
				saveAsImage: {},
				myCsvExport: {
					show: true,
					title: 'Save as csv',
					icon: CSV_LOGO,
					onclick: function() {
						exportAsCSV(opt.names, opt.values, downTitle );
					}
				}
			}
		},
		grid: {
			left: '0',
			right: '4%',
			bottom: '3%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			data: opt.times
			/*type: 'value',
			 boundaryGap: [0, 0.01]*/
		},
		yAxis: {
			type: 'value',
			boundaryGap: [0, 0.01]
		},
		series:function(){
			var serie=[];
			var colorList = ['rgba(45,255,115,0.4)','rgba(62,112,201,0.4)'];
			for( var i=0; i<opt.series.length; i++){
				var item={
					name: opt.series[i].name,
					type: 'line',
					stack: '总量',
					itemStyle: {
						normal: {
							color: colorList[i]
						}
					},
					label: {
						normal: {
							show: true,
							position: 'inside'
						}
					},

					data: opt.series[i].value
				}
				serie.push(item);
			};
			return serie;
		}()

		/*[
		 {
		 name:'value',
		 type: 'bar',
		 data: opt.values
		 }
		 ]*/
	};

	chart.setOption(option);

	return chart;
}

/*
 * opt.divId - map div id
 * opt.data  - map data
 */
function createMap(opt) {
    var chart = echarts.init(document.getElementById(opt.divId));
    $.getJSON('/templates/ppspconsole/js/india.geo.json', function(map) {
        echarts.registerMap('india', map);
        chart.setOption({
            title: {
                text: 'New Users per state',
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data:['New Users']
            },
            visualMap: {
                min: 0,
                max: 50000,
                left: 'left',
                top: 'bottom',
                text: ['High','Low'],
                calculable: true
            },
            toolbox: {
                    show: true,
                    orient: 'vertical',
                    left: 'right',
                    top: 'center',
                    feature: {
                        saveAsImage: {}
                    }
            },
            series: []
        });
    });
    
    return chart;
}

function updateMap(chart, opt) {
    if (opt.data.length == 0)
        return ;
        
    var stateData = [];
    for (var i = 0; i < opt.data.data.length; i++) {
        stateData.push({
            name: opt.data.data[i].state,
            value: opt.data.data[i].count
        });
    }
    
    var option = {
        series: [
        {
            name: 'New Users',
            type: 'map',
            mapType: 'india',
            roam: false,
            label: {
                normal: {
                    show: false
                },
                emphasis: {
                    show: true
                }
            },
            data: stateData
        }
    ]};
    
    chart.setOption(option);
}

